from datetime import datetime, date, timedelta
import time


def ts_to_time_str(ts=None, time_format='%Y-%m-%d %H:%M:%S', offset=0):
    try:
        ts = int(ts)
    except:
        ts = int(time.time())
    if offset != 0:
        ts = int(time.time()) + offset
    time_arr = time.localtime(ts)
    return time.strftime(time_format, time_arr)


def mts_to_time_str(time_format='%y%m%d%H%M%S%f'):
    dt = datetime.now()
    return dt.strftime(time_format)


def time_str_to_ts(time_str, time_format='%Y-%m-%d', offset=0):
    ts = 0
    try:
        date_struct_time = time.strptime(time_str, time_format)
        ts = int(time.mktime(date_struct_time)) + offset
    except Exception as e:
        print(e)
    return ts


def date_str(offset=None, time_format='%Y-%m-%d'):
    if offset is None:
        offset = {
            'days': -1
        }
    _date_str = ''
    try:
        _date_str = (date.today() + timedelta(**offset)).strftime(time_format)
    except Exception as e:
        print(e)
    return _date_str


def date_ts(offset=None, time_format='%Y-%m-%d'):
    _date_ts = 0
    _date_str = date_str(offset, time_format)
    if _date_str != '':
        _date_ts = time_str_to_ts(_date_str, time_format)
    return _date_ts


def get_mon_range(mon=0):
    d = date.today()
    year = d.year
    if mon == 0:
        mon = d.month
    mon_str = str(mon).rjust(2, '0')
    mon_start_date = '{}-{}-01'.format(year, mon_str)
    mon += 1
    if mon == 13:
        year += 1
        mon = 1
    mon_str = str(mon).rjust(2, '0')
    next_mon_start_date = '{}-{}-01'.format(year, mon_str)
    return mon_start_date, next_mon_start_date


def get_offset_date_of_the_month(offset=0):
    _, next_mon_start_str = get_mon_range()
    next_mon_start_ts = time_str_to_ts(next_mon_start_str, offset=-86400)
    return int(ts_to_time_str(next_mon_start_ts, time_format='%d')) + offset
